package com.smt.threenationkill.web;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.smt.threenationkill.domain.Player;
import com.smt.threenationkill.service.ThreeNationKillService;


public class PlayerListController extends AbstractController {

	Logger logger = Logger.getLogger(PlayerListController.class);

	private ThreeNationKillService service;
	
	public void setService(ThreeNationKillService service) {
		this.service = service;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		Resource resource = new ClassPathResource("test.txt");
		File file = null;
		try {
			file = resource.getFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String jsp = getView(req.getRequestURI());
		ModelAndView mav = new ModelAndView(jsp);
		
		if (service.getAllGames() == null || service.getAllGames().size() == 0){
			service.loadAndProcessGamesFromFile(file);	
		}
		List<Player> players= service.getAllPlayers();
		BigDecimal total = BigDecimal.ZERO;
		for (Player player: players){
			total = total.add(player.getTotalPoints());
		}
		System.out.println("The sum of total="+total);
		mav.addObject("players", players);
		return mav;
	}

	
	/**
	 * Returns the name of view to be displayed based on the requestURI
	 * @param requestURI the request URI
	 * @return the name of view to be displayed based on the requestURI
	 */
	private static String getView(String requestURI) {
		if (requestURI.contains("playerListNoPoint.do")){
			return "playerListNoPoint";
		}
		return "playerList";
	}
	
	

}
